package com.yunxi.service.dubboService.impl.sat;

import com.alibaba.cloud.context.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.dealer.pojo.PartnerVO;
import com.yunxi.model.sat.*;
import com.yunxi.sat.pojo.SatCustomerClueVO;
import com.yunxi.sat.pojo.SatCustomerFollowVO;
import com.yunxi.sat.pojo.SatLostApplyVO;
import com.yunxi.sat.pojo.SatMessAddVO;
import com.yunxi.sat.service.SatLostApplyDubboService;
import com.yunxi.service.localService.sat.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 客户战败申请 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-07-11
 */
public class SatLostApplyDubboServiceImpl implements SatLostApplyDubboService {

    @Autowired
    @Qualifier(value = "satLostApplyServiceImpl")
    SatLostApplyService satLostApplyService;

    @Autowired
    @Qualifier(value = "satCustomerClueServiceImpl")
    SatCustomerClueService satCustomerClueService;

    @Autowired
    @Qualifier(value = "partnerCustomerServiceImpl")
    PartnerCustomerService partnerCustomerService;

    @Autowired
    @Qualifier(value = "partnerCustomerHisServiceImpl")
    PartnerCustomerHisService partnerCustomerHisService;

    @Autowired
    @Qualifier(value = "satCustomerFollowServiceImpl")
    SatCustomerFollowService satCustomerFollowService;

    @Autowired
    @Qualifier(value = "msgTemplateServiceImpl")
    MsgTemplateService msgTemplateService;

    @Autowired
    @Qualifier(value = "satMessServiceImpl")
    SatMessService satMessService;


    @Override
    public SatLostApplyVO getById(String id) throws Exception {
        SatLostApply satLostApply = satLostApplyService.getById(id);
        if(satLostApply != null){
            SatLostApplyVO satLostApplyVO = new SatLostApplyVO();
            BeanUtils.copyProperties(satLostApply, satLostApplyVO);
            return satLostApplyVO;
        }
        else {
            throw new Exception("操作失败,无法根据id:"+id+"找到对应战败申请!");
        }
    }

    @Override
    public SatLostApplyVO getInfoById(String id) throws Exception {
        return satLostApplyService.getInfoById(id);
    }

    @Override
    public void saveOrUpdate(SatLostApplyVO satLostApplyVO,LoginInfo loginInfo) throws Exception {
        setPartnerCode(satLostApplyVO, loginInfo);
        satLostApplyVO.setCreateBy(loginInfo.getUserCode());
        satLostApplyVO.setUpdateBy(loginInfo.getUserCode());
        SatLostApply satLostApply = new SatLostApply();
        BeanUtils.copyProperties(satLostApplyVO, satLostApply);
        //根据客户编号查询战败申请次数
        QueryWrapper<SatLostApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_NO",satLostApply.getCustomerNo());
        queryWrapper.eq("PARTNER_CODE",satLostApply.getPartnerCode());
        List<SatLostApply> list = satLostApplyService.list(queryWrapper);
        if(list != null && list.size() > 0){
            satLostApply.setApplyCount(list.size()+1);
        }
        satLostApplyService.saveOrUpdate(satLostApply);
    }

    @Override
    public void removeById(String id) {
        satLostApplyService.removeById(id);
    }

    @Override
    public PageInfo<SatLostApplyVO> findPageByVO(SatLostApplyVO satLostApplyVO, Integer pageNum, Integer pageSize, LoginInfo loginInfo) throws Exception {
        setPartnerCode(satLostApplyVO, loginInfo);
        PageInfo<SatLostApplyVO> pageInfo = satLostApplyService.pageByVo(satLostApplyVO, pageNum, pageSize);
        return pageInfo;
    }



    @Override
    public void removeByListVo(List<SatLostApplyVO> satLostApplyVOList) throws Exception {
        satLostApplyService.removeByListVo(satLostApplyVOList);
    }

    @Override
    public List listByVo(SatLostApplyVO satLostApplyVO) {
        return satLostApplyService.listByVo(satLostApplyVO);
    }

    @Override
    public void del(List<String> list, String createBy) throws Exception {
        if(list != null && list.size() > 0){
            for (String id : list){
                SatLostApply byId = satLostApplyService.getById(id);
                if(byId != null){
                    byId.setIsDel(1);
                    byId.setUpdateBy(createBy);
                    satLostApplyService.saveOrUpdate(byId);
                }
                else {
                    throw new Exception("操作失败,无法根据id:"+id+"找到对应战败申请!");
                }
            }
        }
        else {
            throw new Exception("操作失败,list为空!");
        }
    }

    /**
     * 同意战败
     * @param list
     * @param approveUser
     * @throws Exception
     */
    @Override
    public String agree(List<String> list, String approveUser,String roleCode) throws Exception {
        String msg = null;
        if(list != null && list.size() > 0){
            QueryWrapper<MsgTemplate> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("TYPE",12);
            MsgTemplate msgTemplate = msgTemplateService.getOne(queryWrapper);
            for (String id : list){
                SatLostApply byId = satLostApplyService.getById(id);
                if(byId != null){
                    //校验该客户未存在未完成的订单,才能同意战败或分配.
                    Integer orderSum = satLostApplyService.queryCustomerOrder(byId);//该客户未完成的订单数量
                    if(orderSum >0){
                        msg = "该客户有未完成的订单,请确认后重试!";
                        //更新战败申请单状态为取消
                        byId.setApplyOrderStatus(5);
                        satLostApplyService.saveOrUpdate(byId);
                    }
                    else{
                        //申请次数大于等于2才能同意战败
                        Integer applyCount = byId.getApplyCount();
                        if(applyCount != null && applyCount<2){
                            throw new Exception("操作失败,申请战败次数:"+applyCount+"未达到两次及以上!");
                        }
                        byId.setApplyOrderStatus(2);//同意战败
                        byId.setApproveUser(approveUser);
                        byId.setApproveTime(new Date());
                        byId.setUpdateBy(approveUser);
                        satLostApplyService.saveOrUpdate(byId);
                        //同意战败,需要生成消息提醒给申请战败的销售顾问
//                        addLostMess(byId,"2");
                        msgPush(roleCode,byId.getCustomerNo(),byId.getApplyUser(),12,"41",byId.getPartnerCode());

                        //清空客户信息上的销售顾问编号
                        //2019.09.02 变更为总经理同意才清空
                        /*String customerNo = byId.getCustomerNo();
                        if(StringUtils.isNotEmpty(customerNo)){
                            satLostApplyService.cleanSalesNo(customerNo);
                        }*/
                        msg = "操作成功!";
                    }
                }
                else{
                    throw new Exception("操作失败,无法根据id:"+id+"找到对应战败申请!");
                }
            }
        }
        else {
            throw new Exception("操作失败,list为空!");
        }
        return msg;
    }

    /**
     * 分配
     * @param list
     * @param getUser
     * @param approveUser
     * @throws Exception
     */
    @Override
    public String dispatch(List<String> list, String getUser, String approveUser,String roleCode) throws Exception {
        String msg = null;
        if(list != null && list.size() >0){
            for (String id : list){
                SatLostApply byId = satLostApplyService.getById(id);
                if(byId != null){
                    //校验该客户未存在未完成的订单,才能同意战败或分配.
                    Integer orderSum = satLostApplyService.queryCustomerOrder(byId);//该客户未完成的订单数量
                    if(orderSum > 0){
                        msg = "该客户有未完成的订单,请确认后重试!";
                        //更新战败申请单状态为取消
                        byId.setApplyOrderStatus(5);
                        satLostApplyService.saveOrUpdate(byId);
                    }
                    else{
                        byId.setApplyOrderStatus(3);//转分配
                        byId.setApproveUser(approveUser);
                        byId.setApproveTime(new Date());
                        byId.setUpdateBy(approveUser);
                        byId.setAssignUser(getUser);
                        satLostApplyService.saveOrUpdate(byId);

                        //2.变更客户与销售顾问的关系,新增客户关系历史
                        setPartnerCustomerRelation(getUser, approveUser, byId);

                        //3.生成消息通知原fellow和新fellow
//                        addLostMess(byId,"7");//战败转分配
//                        byId.setCreateBy(getUser);
//                        addLostMess(byId,"8");//新客户分
                        msgPush(roleCode, byId.getCustomerNo(),byId.getCreateBy(),15,"42",byId.getPartnerCode());
                        msgPush(roleCode, byId.getCustomerNo(),getUser,14,"42",byId.getPartnerCode());

                        //4.变更客户上的销售顾问编号
                        satLostApplyService.updateCustomerSales(byId);

                        msg = "操作成功!";
                    }
                }
                else{
                    throw new Exception("操作失败,无法根据id:"+id+"找到对应战败申请!");
                }
            }
        }
        else {
            throw new Exception("操作失败,list为空!");
        }
        return msg;
    }


    /**
     * 总经理同意战败
     * @param applyId
     * @param userCode
     * @throws Exception
     */
    @Override
    public void mAgree(String applyId, String userCode,String roleCode) throws Exception {
        SatLostApply satLostApply = satLostApplyService.getById(applyId);
        if(satLostApply == null)throw new Exception("操作失败,无法根据主键:"+applyId+"找到对应战败记录!");
        String applyUser = satLostApply.getApplyUser();//同意战败的销售经理编号
        satLostApply.setApplyOrderStatus(4);//同意战败
        satLostApply.setApproveUser(userCode);
        satLostApply.setApproveTime(new Date());
        //1.更新战败申请单状态
        satLostApplyService.saveOrUpdate(satLostApply);

        //2.更新客户状态为战败
        SatCustomerFollowVO satCustomerFollowVO = new SatCustomerFollowVO();
        satCustomerFollowVO.setCustomerNo(satLostApply.getCustomerNo());
//        satCustomerFollowVO.setNewCustlevel("7");
        satCustomerFollowVO.setCustStatus(2);//20190902 变更战败为客户状态,而不是客户级别
        satCustomerFollowVO.setPartnerCode(satLostApply.getPartnerCode());
        satCustomerFollowService.updateCustomerLevel(satCustomerFollowVO);

        //3.生成消息给申请的销售顾问
//        addLostMess(satLostApply,"2");//同意战败
////        satLostApply.setCreateBy(applyUser);
////        addLostMess(satLostApply,"2");//同意战败
        msgPush(roleCode,satLostApply.getCustomerNo(),satLostApply.getApplyUser(),24,"43",satLostApply.getPartnerCode());

        //4.清空客户信息上的销售顾问编号
        String customerNo = satLostApply.getCustomerNo();
        if(StringUtils.isNotEmpty(customerNo)){
            satLostApplyService.cleanSalesNo(customerNo);
        }
    }

    /**
     * 总经理驳回
     * @param applyId
     * @param userCode
     * @throws Exception
     */
    @Override
    public void mReject(String applyId, String userCode,String roleCode) throws Exception {
        SatLostApply satLostApply = satLostApplyService.getById(applyId);
        if(satLostApply == null)throw new Exception("操作失败,无法根据主键:"+applyId+"找到对应战败申请记录!");
        String approveUser = satLostApply.getApproveUser();//同意战败的销售经理编号
        satLostApply.setApplyOrderStatus(5);
        satLostApply.setApproveUser(userCode);
        satLostApply.setApproveTime(new Date());
        //1.更新战败申请状态
        satLostApplyService.saveOrUpdate(satLostApply);
        //3.生成消息给申请的销售顾问
//        addLostMess(satLostApply,"9");
//        satLostApply.setCreateBy(approveUser);
//        addLostMess(satLostApply,"9");
        msgPush(roleCode,satLostApply.getCustomerNo(),satLostApply.getApplyUser(),25,"44",satLostApply.getPartnerCode());
    }

    /**
     * 根据客户编号查询是否在申请战败中
     * @param custoemrNo
     * @param partnerCode
     * @return false 不在申请战败中,true申请战败中
     * @throws Exception
     */
    @Override
    public Boolean lostStatus(String custoemrNo, String partnerCode) throws Exception {
        Boolean isInLost = false;
        QueryWrapper<SatLostApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_NO",custoemrNo);
        queryWrapper.eq("PARTNER_CODE",partnerCode);
        queryWrapper.eq("APPLY_ORDER_STATUS",1);
        List<SatLostApply> list = satLostApplyService.list(queryWrapper);
        if(list != null && list.size() > 0) isInLost = true;
        return isInLost;
    }

    /**
     * 设置渠道商代码
     * @param satLostApplyVO
     * @param loginInfo
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    private void setPartnerCode(SatLostApplyVO satLostApplyVO, LoginInfo loginInfo) throws IllegalAccessException, InvocationTargetException {
        Object partner = loginInfo.getPartner();
        if(partner != null){
            PartnerVO partnerVO = new PartnerVO();
            org.apache.commons.beanutils.BeanUtils.copyProperties(partnerVO,partner);
            satLostApplyVO.setPartnerCode(partnerVO.getPartnerCode());
        }
    }

    /**
     * 维护客户与销售顾问关系,历史
     * @param getUser
     * @param approveUser
     * @param byId
     */
    private void setPartnerCustomerRelation(String getUser, String approveUser, SatLostApply byId) {
        String clueId = byId.getClueId();
        SatCustomerClue satCustomerClue = satCustomerClueService.getById(clueId);
        if(satCustomerClue != null){
            String customerNo = satCustomerClue.getCustomerNo();
            QueryWrapper<PartnerCustomer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("CUSTOMER_NO",customerNo);
            PartnerCustomer partnerCustomer = partnerCustomerService.getOne(queryWrapper);
            String userCode = satCustomerClueService.getUserCodeByName(getUser);
            if(partnerCustomer != null){
                partnerCustomer.setSalesConsultantNo(userCode);
                partnerCustomer.setUpdateBy(approveUser);
            }
            else {
                partnerCustomer = new PartnerCustomer();
                partnerCustomer.setCustomerNo(customerNo);
                partnerCustomer.setSalesConsultantNo(userCode);
                partnerCustomer.setCreateBy(approveUser);
                partnerCustomer.setPartnerCode(byId.getPartnerCode());
            }
            partnerCustomerService.saveOrUpdate(partnerCustomer);

            PartnerCustomerHis partnerCustomerHis = new PartnerCustomerHis();
            BeanUtils.copyProperties(partnerCustomer,partnerCustomerHis);
            partnerCustomerHis.setHisId(null);
            partnerCustomerHisService.saveOrUpdate(partnerCustomerHis);
        }
    }


    /**
     *  生成消息
     * @param roleCode
     * @param salesNo
     * @param msgType
     * 客户编号
     * 消息类型
     * 消息所属销售顾问编号
     * 操作者角色代码
     * 模板类型
     */
    private void msgPush(String roleCode, String customerNo,String salesNo,Integer templeType,String msgType,String partnerCode) throws InvocationTargetException, IllegalAccessException {
        SatCustomerClueVO satCustomerClueVO = new SatCustomerClueVO();
        satCustomerClueVO.setCustomerNo(customerNo);
        satCustomerClueVO.setPartnerCode(partnerCode);
        String customerName = satCustomerClueService.getCustomerNameByNo(satCustomerClueVO);
        SatMessAddVO satMessAddVO = new SatMessAddVO();
        satMessAddVO.setType(msgType);
        satMessAddVO.setTemplateType(templeType);
        satMessAddVO.setCustomerName(customerName);
        satMessAddVO.setCustomerNo(customerNo);
        satMessAddVO.setSalesConsultantNo(salesNo);
        satMessAddVO.setReceiveRoleCode("rolePartnerSale");
        satMessAddVO.setOperaRoleCode(roleCode);
        satMessService.newMess(satMessAddVO);
    }
}
